var Jimp = require("jimp");
var fs = require('fs');
const path = require('path');

const MIN_SIZE = 192;
const SIZES_ANDROID = [192,144,96,72,48,32];
const SIZES_IOS = [180,167,152,144,120,114,100,87,83.5,80,76,72,60,58,57,50,40,29,20];

if (!process.argv || process.argv.length < 4) {
	console.log('useage: node resize.js /YOUR/SOURCE/IMAGE/FILE /YOUR/OUTPUT/DIRECTORY');
	return;
}
console.log(process.argv);

var src = process.argv[2];
var dst = process.argv[3];

function resizeTo(src, newSize, subdir) {
	Jimp.read(src, function (err, img) {
		if (err) {
			console.log(err);
			return;
		}
		if (img.bitmap.width < MIN_SIZE || img.bitmap.height < MIN_SIZE) {
			console.log('min size is ' + MIN_SIZE);
			return;
		}
		if (img.getMIME() != Jimp.MIME_PNG) {
			console.log("must be PNG");
			return;
		}
		let outFile = dst + '/'+ subdir +'/icon-' + newSize + '.png';
		img.resize(newSize, newSize)
			.write(outFile, function (err, jimp) {
				if (err) {
					console.log(err);
					return;
				}
				console.log('Saved ' + outFile);
			});
	});
}

if (fs.existsSync(src) && fs.existsSync(dst)) {
	Jimp.read(src, function (err, img) {
		if (err) {
			console.log(err);
			return;
		}
		if (img.bitmap.width < MIN_SIZE || img.bitmap.height < MIN_SIZE) {
			console.log('min size is ' + MIN_SIZE);
			return;
		}
		if (img.getMIME() != Jimp.MIME_PNG) {
			console.log("must be PNG");
			return;
		}
		for(let i = 0; i < SIZES_ANDROID.length; i++) {
			resizeTo(src, SIZES_ANDROID[i], 'android');
		}
		for(let i = 0; i < SIZES_IOS.length; i++) {
			resizeTo(src, SIZES_IOS[i], 'ios');
		}
	});
} else {
	console.log('Source image or destination directory does NOT exist');
}
